/**
 * 
 */
package com.app.mvc.action.corndbaction;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.app.service.ICornDBExcelService;
import com.app.service.ICornDBService;
import com.app.service.IResultDnaPoint;
import com.app.service.vo.CornDbDnaExcelVo;
import com.app.service.vo.CornDbDnaVo;
import com.app.service.vo.DNAVo;
import com.app.service.vo.SelectCornVo;
import com.app.util.ReuqestToVo;
import com.app.util.TwoDimensionCode;

/**
 * @author Administrator
 * 处理种子库点位信息
 */
@RequestMapping(value="/test")
@Controller
public class CornDbAction {
	
	@Value("#{address['address']}")
	private String address; 
	//种子库最大个数
	@Value("#{address['cornDNACount']}")
	private int cornDNACount;
	//查询最大次数
	@Value("#{address['cornDNASelectCount']}")
	private int cornDNASelectCount;
	/**
	 * 
	 */
	public CornDbAction() {
		logger.info(this.getClass().getName()+" loader");
	}
	
	private static Logger logger = Logger.getLogger(CornDbAction.class);

	@Autowired
	private ICornDBService corndbservice;
	
	@Autowired
	private ICornDBExcelService cornDbExcelService;
	
	/**
	 * 获取具体的dna解析结果
	 */
	@Autowired
	private IResultDnaPoint dnapoint;
	
	@Autowired
	private TwoDimensionCode imagecreate;
	/**
	 * 添加种子库信息
	 * @param request
	 * @return
	 */

	@RequestMapping(value="/add.form")
	public String cornAdd(@RequestParam("file") MultipartFile file,HttpServletRequest request,HttpServletResponse response)
	{
		logger.info("种子信息添加");
		
		String message ="";	
		JSONObject jo = new JSONObject();
		JSONArray ja = new JSONArray();
		int i = this.corndbservice.statCornDbDnaVoByParam("");
		if(i>=cornDNACount){
			message="样品个数已达到上限";
			try {
				jo.put("error", message);
				ja.add(jo);
				response.getWriter().print(ja);
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}
		if(file==null || file.getSize()==0){
			message="请上传样品execl";
			try {
				jo.put("error", message);
				ja.add(jo);
				response.getWriter().print(ja);
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}
		CornDbDnaVo vo = new CornDbDnaVo();		
		String excelpath = request.getSession().getServletContext().getRealPath("")+"\\excelroot\\";
		String imagepath = request.getSession().getServletContext().getRealPath("")+"\\excelroot\\";		
		String fileType=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
		String filename="/"+System.currentTimeMillis()+fileType;
		String uploadPath=excelpath+filename;
		try {

			if (fileType.endsWith("xlsx")||fileType.endsWith("xls")) {
				FileCopyUtils.copy(file.getBytes(),new File(uploadPath));
				DNAVo dnavo = (DNAVo) this.dnapoint.getDNAVo(new FileInputStream(uploadPath), "corn");
				if("".equals(dnavo.getDnaName())){
					message="样品名称不能为空，请修改后再上传";
					try {
						jo.put("error", message);
						ja.add(jo);
						response.getWriter().print(ja);
					} catch (IOException e) {
						e.printStackTrace();
					}
					return null;
				}
				int i1 = this.corndbservice.statCornDbDnaVoByParam(" and dnaName = '"+dnavo.getDnaName()+"'");
				if(i1>0){
					message="样品名称重复，请修改后再上传";
					try {
						jo.put("error", message);
						ja.add(jo);
						response.getWriter().print(ja);
					} catch (IOException e) {
						e.printStackTrace();
					}
					return null;
				}
				if("".equals(dnavo.getDnaCoder())){
					message="样品编号不能为空，请修改后再上传";
					try {
						jo.put("error", message);
						ja.add(jo);
						response.getWriter().print(ja);
					} catch (IOException e) {
						e.printStackTrace();
					}
					return null;
				}
				int i2 = this.corndbservice.statCornDbDnaVoByParam(" and dnaCoder = '"+dnavo.getDnaCoder()+"'");
				if(i2>0){
					message="样品编号重复，请修改后再上传";
					try {
						jo.put("error", message);
						ja.add(jo);
						response.getWriter().print(ja);
					} catch (IOException e) {
						e.printStackTrace();
					}
					return null;
				}
				
				if("".equals(dnavo.getDnasource())){
					message="样品来源不能为空，请修改后再上传";
					try {
						jo.put("error", message);
						ja.add(jo);
						response.getWriter().print(ja);
					} catch (IOException e) {
						e.printStackTrace();
					}
					return null;
				}
				int i3 = this.corndbservice.statCornDbDnaVoByParam(" and dnaSource = '"+dnavo.getDnasource()+"'");
				if(i3>0){
					message="样品来源重复，请修改后再上传";
					try {
						jo.put("error", message);
						ja.add(jo);
						response.getWriter().print(ja);
					} catch (IOException e) {
						e.printStackTrace();
					}
					return null;
				}
				
//				Map<String, Integer> rsmap = dnavo.getValues();
				 String imagemsg = "DNA";
//						 List<String> list = new ArrayList(rsmap.keySet());
//						 Collections.sort(list);
//						 for(String k:list)
//						 {
//							 imagemsg = imagemsg+k+";";
//						 }
//						logger.info("create TwoDimension");
				String images = "twoimages"+UUID.randomUUID()+".png";
//				System.out.println(">>>"+imagemsg);
				this.imagecreate.encoderQRCode(imagemsg, imagepath+images,"png");
				vo.setDnaImage("/excelroot/"+images);
				vo.setFilePath(filename);
				vo.setDnaCoder(dnavo.getDnaCoder());
				vo.setPointCount((int) dnavo.getPointsum());
				vo.setDnaName(dnavo.getDnaName());
				vo.setDnaType(dnavo.getDnatype());
				vo.setDnaSource(dnavo.getDnasource());
				vo.setDnaAddress(address);
				vo.setCreateUserId(request.getSession().getAttribute("loginname").toString());
				vo.setDnaData(dnavo.getDnaData());
			}else{
				message="请上传execl文件";
				try {
					jo.put("error", message);
					ja.add(jo);
					response.getWriter().print(ja);
				} catch (IOException e) {
					e.printStackTrace();
				}
				return null;
			}
			vo.setCreateTime(new Timestamp(System.currentTimeMillis()));
			this.corndbservice.saveDANVo(vo);
		} catch (Exception e) {
			e.printStackTrace();
			message="样品execl文件格式不对，请重新下载模板";
			try {
				jo.put("error", message);
				ja.add(jo);
				response.getWriter().print(ja);
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			return null;
		}
		return this.cornList(request);
	}

	@RequestMapping(value="addpage.form")
	public String cornAddPagt()
	{
		logger.info("展现种子库添加信息");
		return "corntest/corn-add";
	}
	
	/**
	 * 通过指定id获取具体样本信息
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/editshow.form")
	public String cornEditShow(@RequestParam(value="id") String id,@RequestParam(value="execlId") String execlId,HttpServletRequest request)
	{
		logger.info("依据id获取信息 ");
		CornDbDnaVo vo = this.corndbservice.getCornDbDnaVoById(id);
		request.setAttribute("corn-dbvo", vo);
		CornDbDnaVo vo1=null;
		if(execlId!=null&&!"".equals(execlId)){
			CornDbDnaExcelVo cdevo = this.cornDbExcelService.getById(execlId);
			vo1 = new CornDbDnaVo();
			BeanUtils.copyProperties(cdevo,vo1);
		}
		request.setAttribute("corn-dnvvo", vo.getPointMsg(vo1,2));
		request.setAttribute("isExecl", 2);
		return "/corntest/corn-test-show";
	}
	/**
	 * 通过指定id获取具体样本信息
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/editshowExecl.form")
	public String cornEditShowExecl(@RequestParam(value="id") String id,HttpServletRequest request){
		CornDbDnaExcelVo cdevo = this.cornDbExcelService.getById(id);
		CornDbDnaVo vo = new CornDbDnaVo();
		BeanUtils.copyProperties(cdevo,vo);
		request.setAttribute("corn-dbvo", vo);
		request.setAttribute("corn-dnvvo", vo.getPointMsg(null,1));
		request.setAttribute("isExecl", 1);
		return "/corntest/corn-test-show";
	}
	
	/**
	 * 展现信息查询页面
	 * @return
	 */
	@RequestMapping(value="selectshow.form")
	public String showSelectPage()
	{
		logger.info("展现种子信息查询");
		return "corntest/corn-select";
	}
	
	/**
	 * 展现用户查询结果
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/cornSelect.form")
	public String resultShow(HttpServletRequest request)
	{
		SelectCornVo vo = new SelectCornVo();
		ReuqestToVo.getVoFromRequest(request, vo);
		StringBuilder sb = new StringBuilder();
		if(vo.getDnaName()!=null && !"".equals(vo.getDnaName())){
			sb.append(" and dnaName like '%");
			sb.append(vo.getDnaName());
			sb.append("%'");			
		}
		if(vo.getDnaCoder()!=null && !"".equals(vo.getDnaCoder())){
			sb.append(" and dnaCoder like '%");
			sb.append(vo.getDnaCoder());
			sb.append("%'");			
		}
		if(vo.getDnaType()!=null  && !"".equals(vo.getDnaType()) && !"0".equals(vo.getDnaType())){
			
			sb.append(" and dnaType like '%");
			sb.append(vo.getDnaType());
			sb.append("%'");			
		}
		if(vo.getDnaSource()!=null  && !"".equals(vo.getDnaSource())){
			
			sb.append(" and dnaSource like '%");
			sb.append(vo.getDnaSource());
			sb.append("%'");			
		}
		
		request.setAttribute("corn-db-list", this.corndbservice.listCornDbDnaVoByParam(sb.toString()));
		return "corntest/corn-show";
	}
	/**
	 * 展现用户模板查询页面
	 * @return
	 */
	@RequestMapping(value="/selectByMbPage.form")
	public String resultShowByMbShowPage()
	{
		return "corntest/corn-select-mb";
	}
	
	/**
	 * 根据具体dna信息模板进行查询
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/selectByMb.form")
	public String resultShowByMb(@RequestParam("file") MultipartFile file,HttpServletRequest request,HttpServletResponse response)
	{

		String message ="";	
		JSONObject jo = new JSONObject();
		JSONArray ja = new JSONArray();
		SelectCornVo vo = new SelectCornVo();
		if(file==null || file.getSize()==0){
			message="请上传待测样品execl";
			try {
				jo.put("error", message);
				ja.add(jo);
				response.getWriter().print(ja);
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}
		if(cornDNASelectCount< this.cornDbExcelService.statByParam("")){
			message="查询次数已满，请联系管理员";
			try {
				
				jo.put("error", message);
				ja.add(jo);
				response.getWriter().print(ja);
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}
		String excelpath = request.getSession().getServletContext().getRealPath("")+"\\excelroot\\";
		String pointCount = "0";
		String imagepath = request.getSession().getServletContext().getRealPath("")+"\\excelroot\\";
		
		String fileType=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
		String filename="/"+System.currentTimeMillis()+fileType;
		String uploadPath=excelpath+filename;
		
		String execlId="";
		try {	
			if (filename.endsWith("xlsx")||filename.endsWith("xls")) {
				FileCopyUtils.copy(file.getBytes(),new File(uploadPath));
				//对比前先进行excel入库操作
				execlId = addExcel(excelpath,imagepath,filename);				
				DNAVo dnavo = (DNAVo) this.dnapoint.getDNAVo(file.getInputStream(), "corn");						
				vo.setCount(""+dnavo.getPointsum());
			}			
		} catch (Exception e) {
			e.printStackTrace();
		}
		vo.setDnaName(request.getParameter("dnaName"));
		vo.setDnaCoder(request.getParameter("dnaCoder"));
		vo.setDnaType(request.getParameter("dnaType"));
		vo.setDnaSource(request.getParameter("dnaSource"));	
		pointCount = new String(request.getParameter("pointCount"));
		StringBuilder sb = new StringBuilder();
		if(vo.getDnaName()!=null && !"".equals(vo.getDnaName())){
			sb.append(" and dnaName like '%");
			sb.append(vo.getDnaName());
			sb.append("%'");			
		}
		if(vo.getDnaCoder()!=null && !"".equals(vo.getDnaCoder())){
			
			sb.append(" and dnaCoder like '%");
			sb.append(vo.getDnaCoder());
			sb.append("%'");			
		}
	/*	if(vo.getDnaType()!=null  && !"".equals(vo.getDnaType()) && !"0".equals(vo.getDnaType())){
			
			sb.append(" and dnaType like '%");
			sb.append(vo.getDnaType());
			sb.append("%'");			
		}*/
		if(vo.getDnaSource()!=null  && !"".equals(vo.getDnaSource())){
			
			sb.append(" and dnaSource like '%");
			sb.append(vo.getDnaSource());
			sb.append("%'");			
		}
		/*if(vo.getCount()!=null && pointCount!=null  && !"".equals(pointCount)){			
			sb.append(" and pointCount >= ");
			sb.append(Integer.parseInt(vo.getCount())-Integer.parseInt(pointCount));
			sb.append(" and ");
			sb.append(" pointCount <= ");		
			sb.append(Integer.parseInt(vo.getCount())+Integer.parseInt(pointCount));
		}*/
		List<CornDbDnaVo> list = this.corndbservice.listCornDbDnaVoByParam(sb.toString());
		CornDbDnaVo _c = new CornDbDnaVo();
		BeanUtils.copyProperties(cornDbExcelService.getById(execlId), _c);
		list.add(0, _c);
	    request.setAttribute("corn-db-list", list);
	
		return "corntest/corn-show-mb"	;
	}
	/**
	 * 展现现有种子库信息
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/allshow.form")
	public String cornList(HttpServletRequest request)
	{
		request.setAttribute("corn-db-list", this.corndbservice.getAll());
		return "corntest/corn-show";
	}
	/**
	 * 种子信息对比的EXCEL进行入库
	 * @return
	 */
	public String addExcel(String excelpath,String imagepath,String endfilename)
	{
		logger.info("种子信息添加");
		CornDbDnaExcelVo vo = new CornDbDnaExcelVo();
		DiskFileItemFactory factory = new DiskFileItemFactory();
		try {		
			DNAVo dnavo = (DNAVo) this.dnapoint.getDNAVo(new FileInputStream(excelpath +endfilename), "corn");
			String imagemsg = "DNA";
			String images ="twoimages"+UUID.randomUUID()+".png";
			this.imagecreate.encoderQRCode(imagemsg, imagepath+images,"png");
			vo.setDnaImage(images);
			vo.setFilePath(endfilename);
			vo.setDnaCoder(dnavo.getDnaCoder());
			vo.setPointCount((int) dnavo.getPointsum());
			vo.setDnaName(dnavo.getDnaName());
			vo.setDnaType(dnavo.getDnatype());
			vo.setDnaSource(dnavo.getDnasource());
			vo.setDnaAddress(address);
		//	vo.setCreateUserId(request.getSession().getAttribute("loginname").toString());
			vo.setCreateTime(new Timestamp(System.currentTimeMillis()));	
			vo.setDnaData(dnavo.getDnaData());
			return this.cornDbExcelService.saveDANExcelVo(vo);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "0";
	}
	public ICornDBService getCorndbservice() {
		return corndbservice;
	}
	public void setCorndbservice(ICornDBService corndbservice) {
		this.corndbservice = corndbservice;
	}

	public IResultDnaPoint getDnapoint() {
		return dnapoint;
	}

	public void setDnapoint(IResultDnaPoint dnapoint) {
		this.dnapoint = dnapoint;
	}

	public TwoDimensionCode getImagecreate() {
		return imagecreate;
	}

	public void setImagecreate(TwoDimensionCode imagecreate) {
		this.imagecreate = imagecreate;
	}

	public ICornDBExcelService getCornDbExcelService() {
		return cornDbExcelService;
	}

	public void setCornDbExcelService(ICornDBExcelService cornDbExcelService) {
		this.cornDbExcelService = cornDbExcelService;
	}
	
	
	
	
}
